package com.chaochis.springboottestdemo.config.rabbitMqConfig;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {

  @Autowired
  private RabbitQueueProperties rabbitQueueProperties;

  @Bean
  public Queue directQueue() {
    return new Queue(rabbitQueueProperties.getQueueName(), true);
  }

  @Bean
  public DirectExchange directExchange() {
    return new DirectExchange(rabbitQueueProperties.getExchangeName(), true, false);
  }

  @Bean
  public Binding bindingDirect() {
    return BindingBuilder.bind(this.directQueue()).to(this.directExchange()).with(rabbitQueueProperties.getRouteKey());
  }

  @Bean(name = "testRabbitMqTemplate")
  public RabbitTemplate myRabbitMqTemplate(ConnectionFactory connectionFactory) {
    var rabbitMqTemplate = new RabbitTemplate();
    rabbitMqTemplate.setConnectionFactory(connectionFactory);
    rabbitMqTemplate.setMandatory(true);
    rabbitMqTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
    rabbitMqTemplate.setConfirmCallback((correlationData, ack, cause) -> {
      System.out.println("ConfirmCallback:     "+"相关数据："+correlationData);
      System.out.println("ConfirmCallback:     "+"确认情况："+ack);
      System.out.println("ConfirmCallback:     "+"原因："+cause);
    });
    rabbitMqTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
      System.out.println("ReturnCallback:     "+"消息："+message);
      System.out.println("ReturnCallback:     "+"回应码："+replyCode);
      System.out.println("ReturnCallback:     "+"回应信息："+replyText);
      System.out.println("ReturnCallback:     "+"交换机："+exchange);
      System.out.println("ReturnCallback:     "+"路由键："+routingKey);
    });
    return rabbitMqTemplate;
  }
}
